﻿using CTM.Web.Data;
using CTM.Web.Models.Input;
using CTM.Web.Repositories;
using System.Collections.Generic;
using System.Linq;

namespace CTM.Web.Services
{
    public interface IOrgService : IApplicationService<Org>
    {
        IEnumerable<Org> GetByUser(string userId);

        IEnumerable<Org> GetByManager(string managerId, bool includeSub = false);
    }

    public class OrgService : ApplicationService<Org>, IOrgService
    {
        private IUnitOfWork unitOfWork;
        private IOrgRepository orgRepository;

        public OrgService(IUnitOfWork unitOfWork, IOrgRepository orgRepository)
            : base(unitOfWork, orgRepository)
        {
            this.unitOfWork = unitOfWork;
            this.orgRepository = orgRepository;
        }

        public IEnumerable<Org> GetByUser(string userId)
        {
            return orgRepository.Get(o => o.Employees.Any(e => e.Id == userId));
        }

        public IEnumerable<Org> GetByManager(string managerId, bool includeSub = false)
        {
            // Execute the query
            var mainOrgs = orgRepository.Get(mo => mo.Manager.Id == managerId);

            if (!includeSub)
            {
                // Only get orgs which are directly managed by this manager
                return mainOrgs;
            }
            else
            {
                // Extract the paths 
                var mainOrgPaths = mainOrgs.Select(mo => mo.Path);

                // Also include sub orgs, which start with main org's path
                // Example: Main Org's Path: \\RBVH\ETI
                //          Sub Org's Path : \\RBVH\ETI\ETI1
                return orgRepository.Get(so => mainOrgPaths.Any(p => so.Path.StartsWith(p)));
            }
        }
    }
}